package com.weiadmin.exception;

import com.weiadmin.response.RestResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 * @author: shizhongyu
 * @date: 2023年03月18日 11:58
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(GlobalException.class)
    public ResponseEntity<?> handleException(GlobalException exception) {
        RestResponse<Object> response = new RestResponse<>();
        return response.error(exception.getMessage(),null);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        // 获取所有校验失败的错误信息，拼接成错误信息字符串
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMsg.append(fieldError.getDefaultMessage()).append(",");
        });
        RestResponse<Object> response = new RestResponse<>();
        return response.error(errorMsg.toString(),null);
    }
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<?> handleException(BindException  e) {
        BindingResult bindingResult = e.getBindingResult();
        RestResponse<Object> response = new RestResponse<>();
        //目前的实现只返回第一个错误
        String msg = bindingResult.getFieldErrors().get(0).getDefaultMessage();
        return response.error(msg);
    }

}
